/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vista;

import Consultas.Logica;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author USUARIO WINDOWS
 */
public class vistaVentas extends javax.swing.JFrame {

    /**
     * Creates new form vistaVentas
     */
    public vistaVentas() throws SQLException {
        initComponents();
        logica = new Logica();
        productos = logica.obtenerProductos();
        if (productos.length != 0) {
            actualizarProductos(productos);
            
        }
        modelo = (DefaultTableModel) TableVenta.getModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLCliente = new javax.swing.JLabel();
        jCProductos = new javax.swing.JComboBox();
        jLProductos = new javax.swing.JLabel();
        jTCliente = new javax.swing.JTextField();
        jLCantidad = new javax.swing.JLabel();
        jTCantidad = new javax.swing.JTextField();
        jBAgregarProducto = new javax.swing.JButton();
        jBConfirmarVenta = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableVenta = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        jLCliente.setText("Cliente");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ventas");
        setBackground(new java.awt.Color(255, 255, 255));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jCProductos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jCProductos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCProductosActionPerformed(evt);
            }
        });
        getContentPane().add(jCProductos, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 140, -1));

        jLProductos.setText("Productos");
        getContentPane().add(jLProductos, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 60, -1, -1));
        getContentPane().add(jTCliente, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 150, 140, -1));

        jLCantidad.setText("Cantidad");
        getContentPane().add(jLCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 100, -1, -1));
        getContentPane().add(jTCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, 140, -1));

        jBAgregarProducto.setText("Agregar producto");
        jBAgregarProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAgregarProductoActionPerformed(evt);
            }
        });
        getContentPane().add(jBAgregarProducto, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 210, 160, -1));

        jBConfirmarVenta.setText("Confirmar venta");
        jBConfirmarVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBConfirmarVentaActionPerformed(evt);
            }
        });
        getContentPane().add(jBConfirmarVenta, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 230, 160, -1));

        TableVenta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Cantidad", "Cliente", "precio", "PrecioTotal"
            }
        ));
        jScrollPane1.setViewportView(TableVenta);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 50, 410, 150));

        jLabel1.setText("Cliente");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 150, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCProductosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCProductosActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCProductosActionPerformed

    private void jBAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAgregarProductoActionPerformed
        // TODO add your handling code here:
        
        modelo.addRow(new Object[]{jCProductos.getSelectedItem(), jTCantidad.getText(), jTCliente.getText(),
            logica.precioProductos[jCProductos.getSelectedIndex()],
            logica.precioProductos[jCProductos.getSelectedIndex()] * Integer.parseInt(jTCantidad.getText())});
        
    }//GEN-LAST:event_jBAgregarProductoActionPerformed

    private void jBConfirmarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBConfirmarVentaActionPerformed
        try {
            // TODO add your handling code here:
            //  logica.ingresarCompra(obtenerTotalCompra(), getIdAdmin(), obtenerIdProveedor("" + tableCompra.getValueAt(0, 1)));
            System.out.println(getIdEmple() );
            logica.ingresarVenta(obtenerTotalVenta(), getIdEmple(), Integer.parseInt(jTCliente.getText()));
            insertarDetalleVenta();
        } catch (SQLException ex) {
            Logger.getLogger(vistaVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_jBConfirmarVentaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(vistaVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(vistaVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(vistaVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(vistaVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new vistaVentas().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(vistaVentas.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TableVenta;
    private javax.swing.JButton jBAgregarProducto;
    private javax.swing.JButton jBConfirmarVenta;
    private javax.swing.JComboBox jCProductos;
    private javax.swing.JLabel jLCantidad;
    private javax.swing.JLabel jLCliente;
    private javax.swing.JLabel jLProductos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTCantidad;
    private javax.swing.JTextField jTCliente;
    // End of variables declaration//GEN-END:variables

    private String[] productos;
    private Logica logica;
    private DefaultTableModel modelo;    
    private int idEmple;
    
    public int getIdEmple() {
        return idEmple;
    }
    
    public void setIdEmple(int idEmple) {
        this.idEmple = idEmple;
    }
    
    public void actualizarProductos(String[] vector) {
        if (vector.length != 0) {
            ComboBoxModel comb = new DefaultComboBoxModel(vector);
            jCProductos.setModel(comb);
            
        }
        
    }

    public double obtenerTotalVenta() {
        
        double total = 0.0;
        for (int i = 0; i < TableVenta.getRowCount(); i++) {
            total += Double.parseDouble("" + TableVenta.getValueAt(i, 4));
        }
        return total;
    }
    
    public int obtenerIdCliente(String idCliente) throws SQLException {
        
        int idClientes = 0;
        for (int i = 0; i < logica.obtenerClientes().length; i++) {
            if (logica.obtenerClientes()[i].equals(idCliente)) {
                idClientes = i + 1;
            }            
        }
        return idClientes;
    }
    
     public void insertarDetalleVenta() throws SQLException {
        Double total = 0.0;
        Double precioUnitario = 0.0;
        for (int j = 0; j < TableVenta.getRowCount(); j++) {
            total = Double.parseDouble(""+ TableVenta.getValueAt(j, 4));                      
            int cantidad = Integer.parseInt((String) TableVenta.getValueAt(j, 1));            
            precioUnitario = Double.parseDouble(""+TableVenta.getValueAt(j, 3));
                
            logica.ingresarDetalleVenta(total, cantidad, obtenerIdProducto("" + TableVenta.getValueAt(0, 0)),precioUnitario);

        }
    
     }
     public int obtenerIdProducto(String nombreProducto) throws SQLException {

        int idProducto = 0;
        for (int i = 0; i < logica.obtenerProductos().length; i++) {
            if (logica.obtenerProductos()[i].equals(nombreProducto)) {
                idProducto = i + 1;
            }
        }
        return idProducto;
    }
}
